// API 基础配置
const API_BASE_URL = 'http://localhost:8080/api'

// 通用请求函数
async function request(url, options = {}) {
  const config = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  }

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config)
    const data = await response.json()
    
    if (data.code === 200) {
      return data.data
    } else {
      throw new Error(data.message || '请求失败')
    }
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

// 商品相关API
export const productAPI = {
  // 获取所有商品
  getAllProducts() {
    return request('/products')
  },

  // 获取有库存的商品
  getAvailableProducts() {
    return request('/products/available')
  },

  // 根据ID获取商品
  getProductById(id) {
    return request(`/products/${id}`)
  },

  // 搜索商品
  searchProducts(name) {
    return request(`/products/search?name=${encodeURIComponent(name)}`)
  },

  // 检查库存
  checkStock(productId, quantity) {
    return request(`/products/${productId}/stock?quantity=${quantity}`)
  },

  // 获取库存不足的商品
  getLowStockProducts(threshold = 5) {
    return request(`/products/low-stock?threshold=${threshold}`)
  }
}

// 预定相关API
export const reservationAPI = {
  // 创建预定
  createReservation(reservationData) {
    return request('/reservations', {
      method: 'POST',
      body: JSON.stringify(reservationData)
    })
  },

  // 确认预定
  confirmReservation(reservationId) {
    return request(`/reservations/${reservationId}/confirm`, {
      method: 'PUT'
    })
  },

  // 取消预定
  cancelReservation(reservationId) {
    return request(`/reservations/${reservationId}/cancel`, {
      method: 'PUT'
    })
  },

  // 完成预定
  completeReservation(reservationId) {
    return request(`/reservations/${reservationId}/complete`, {
      method: 'PUT'
    })
  },

  // 获取用户的预定记录
  getUserReservations(userId) {
    return request(`/reservations/user/${userId}`)
  },

  // 根据状态获取用户的预定记录
  getUserReservationsByStatus(userId, status) {
    return request(`/reservations/user/${userId}/status/${status}`)
  },

  // 根据ID获取预定记录
  getReservationById(reservationId) {
    return request(`/reservations/${reservationId}`)
  },

  // 获取所有预定记录
  getAllReservations() {
    return request('/reservations')
  },

  // 统计用户预定数量
  countUserReservations(userId) {
    return request(`/reservations/user/${userId}/count`)
  },

  // 统计指定状态的预定数量
  countReservationsByStatus(status) {
    return request(`/reservations/count/status/${status}`)
  }
}
